package com.ball.web;

import com.alibaba.fastjson.JSONObject;
import com.ball.entity.Log;
import com.ball.entity.User;
import com.ball.service.LogService;
import com.ball.service.UserService;
import com.ball.service.WalletService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ball.tools.StringUtil.isNull;


@Controller
@RequestMapping("/manage")
public class ManageController extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    WalletService walletService;
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;
    @RequestMapping("")
    public String manage(HttpServletRequest request, Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start, size, "id desc");
        String username = ((User) request.getSession().getAttribute("user")).getUsername();
        JSONObject json = new JSONObject();
        logger.info(username);
        json.put("username", username);
        List<Log> logs = logService.queryLogByUsername(json);
        PageInfo<Log> page = new PageInfo<>(logs);
        m.addAttribute("page", page);
        return "manage";
    }

//    @RequestMapping(value = "/queryMoney", method = RequestMethod.POST, produces = "application/json")
//    @ResponseBody
//    public Map<String, Object> queryMoney(@RequestBody Map<String, Object> map) {
//        Map<String, Object> result = new HashMap<String, Object>();
//        JSONObject json = new JSONObject(map);
//        String username = json.getString("username");
//        System.out.println(username);
//        User user = userService.queryUserByUsername(json);
//        String address = user.getWalletAddress();
//        System.out.println(address);
//        if (isNull(address) || address.equals("null")) {
//            List<String> list = walletService.generate(json);
////            int i = 0;
////            do {
////                try {
////
////                    Thread.sleep(1000);
////                } catch (InterruptedException e) {
////                    e.printStackTrace();
////                }
////                i++;
////            } while (isNull(list.get(1)) && i < 10);
//            do{
//
//            }while (isNull(list.get(1)));
//            System.out.println(list);
//            json.put("log", list.get(1));
//            logService.add(json);
//            address = list.get(1).substring(50, 150);
//            user.setWalletAddress(address);
//            userService.update(user);
//        }
//        String balance = user.getMoney();
//        System.out.println(balance);
//        result.put("result", "1");
//        result.put("address", address);
//        result.put("balance", balance);
//        return result;
//    }

//    @RequestMapping(value = "/generateWallet", method = RequestMethod.POST, produces = "application/json")
//    @ResponseBody
//    public Map<String, Object> generateWallet(@RequestBody Map<String, Object> map) {
//        Map<String, Object> result = new HashMap<String, Object>();
//        JSONObject json = new JSONObject(map);
//        String username = json.getString("username");
//        System.out.println(username);
//        User user = userService.queryUserByUsername(json);
//        List<String> list = walletService.generate(json);
//        int i = 0;
//        do {
//            try {
//
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
////            }
////            i++;
////        } while (isNull(list.get(1)) && i < 10);
////        System.out.println(list);
////        json.put("log", list.get(1));
////        logService.add(json);
////        String address = list.get(1).substring(50, 150);
////        user.setWalletAddress(address);
////        userService.update(user);
////        result.put("result", "1");
////        result.put("address", address);
////        result.put("balance", user.getMoney());
////        return result;
////    }

    /**
     *
     * @param
     *  //map含有name的ajax需要Json格式
     * @return
     */
    @RequestMapping(value = "/reflashMoney", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> reflashMoney(@RequestBody Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        JSONObject json = new JSONObject(map);
        String username = json.getString("username");
        logger.info(username);
        User user = userService.queryUserByUsername(json);
        String address = user.getWalletAddress();
        logger.info(address);
        if (isNull(address) || address.equals("null")) {
            List<String> list1 = walletService.generate(json);
//            int i = 0;
//            do {
//                try {
//
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                i++;
//            } while (isNull(list.get(1)) && i < 10);
            do{

            }while (isNull(list1.get(1)));
            logger.info(list1.toString());
            json.put("log", list1.get(1));
            logService.add(json);
            String  str=list1.get(1);
            address = str.substring(str.indexOf("INFO")+8, str.indexOf("       "));
            user.setWalletAddress(address);
            userService.update(user);
        }
        List<String> list = walletService.balance(json);
//            int i = 0;
//            do {
//                Thread.sleep(1000);
//                i++;
//            } while (isNull(list.get(1)) != true && i < 10);
        do{

        }while (isNull(list.get(1)));
        String money = list.get(1);
        logger.info(money);
        json.put("log", money);
        logService.add(json);
        money = money.substring(money.indexOf("balance") + 9, money.indexOf(","));
        user.setMoney(money);
        userService.update(user);
        logger.info(money);
        result.put("result", "1");
        result.put("balance", money);
        result.put("address", user.getWalletAddress());
        return result;

    }

    @RequestMapping(value = "/transfer", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> transfer(@RequestBody Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        JSONObject json = new JSONObject(map);
        String address = json.getString("address");
        String username = json.getString("username");
        String pay = json.getString("pay");
        logger.info(username + pay + address);
        if (Double.valueOf(pay) > 0.001 && (!address.isEmpty())) {
            List<String> list = walletService.transfer(json);
//            int i = 0;
//            do {
//                try {
//
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                i++;
//            } while (isNull(list.get(1)) && i < 10);
            do{

            }while (isNull(list.get(1)));
            logger.info(list.get(1));
            json.put("log", list.get(1));
            logService.add(json);
            result.put("result", "1");
        }
        result.put("result", "1");
        return result;
    }

}
